<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="600px"
    :before-close="handleClose"
    class="inventory-dialog"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-width="100px"
      @submit.prevent="handleSubmit"
      class="inventory-form"
    >
      <el-form-item label="产品" prop="productId" v-if="!editingItem">
        <el-select 
          v-model="form.productId" 
          placeholder="请选择产品" 
          style="width: 100%"
          @change="handleProductChange"
          class="form-select"
        >
          <el-option
            v-for="product in products"
            :key="product.id"
            :label="`${product.name} (${product.sku})`"
            :value="product.id"
          />
        </el-select>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="当前库存" prop="currentStock">
            <el-input-number 
              v-model="form.currentStock" 
              :min="0" 
              :disabled="!!editingItem"
              style="width: 100%"
              class="form-input-number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" readonly class="form-input" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最低库存" prop="minStock">
            <el-input-number v-model="form.minStock" :min="0" style="width: 100%" class="form-input-number" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高库存" prop="maxStock">
            <el-input-number v-model="form.maxStock" :min="0" style="width: 100%" class="form-input-number" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="库存调整">
        <el-radio-group v-model="adjustType" @change="handleAdjustTypeChange" class="radio-group">
          <el-radio value="increase" class="radio-item">增加</el-radio>
          <el-radio value="decrease" class="radio-item">减少</el-radio>
          <el-radio value="set" class="radio-item">设置为</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="调整数量" prop="adjustAmount" v-if="adjustType !== 'set'">
        <el-input-number 
          v-model="adjustAmount" 
          :min="0" 
          :max="adjustType === 'decrease' ? form.currentStock : undefined"
          style="width: 100%"
          class="form-input-number"
        />
      </el-form-item>
      
      <el-form-item label="调整原因" prop="adjustReason">
        <el-select v-model="adjustReason" placeholder="请选择调整原因" style="width: 100%" class="form-select">
          <el-option label="采购入库" value="purchase" />
          <el-option label="销售出库" value="sale" />
          <el-option label="库存损耗" value="loss" />
          <el-option label="库存盘盈" value="gain" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" class="form-textarea" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose" class="cancel-btn">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting" class="submit-btn">
        {{ editingItem ? '更新' : '保存' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Product {
  id: number
  sku: string
  name: string
  specification: string
  unit: string
}

interface InventoryItem {
  id: number
  productId: number
  sku: string
  productName: string
  specification: string
  currentStock: number
  minStock: number
  maxStock: number
  unit: string
  lastUpdate: string
  status: string
  remark: string
}

const props = defineProps<{
  modelValue: boolean
  editingItem: InventoryItem | null
  products: Product[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', form: any): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitting = ref(false)

const form = ref({
  productId: null as number | null,
  currentStock: 0,
  unit: '',
  minStock: 0,
  maxStock: 0,
  remark: ''
})

const adjustType = ref('set')
const adjustAmount = ref(0)
const adjustReason = ref('')

const dialogTitle = computed(() => {
  return props.editingItem ? '编辑库存记录' : '新增库存记录'
})

const rules = ref<FormRules>({
  productId: [
    { required: true, message: '请选择产品', trigger: 'change' }
  ],
  currentStock: [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ],
  adjustReason: [
    { required: true, message: '请选择调整原因', trigger: 'change' }
  ]
})

// 监听编辑项变化
watch(() => props.editingItem, (newVal) => {
  if (newVal) {
    form.value = { 
      productId: newVal.productId,
      currentStock: newVal.currentStock,
      unit: newVal.unit,
      minStock: newVal.minStock,
      maxStock: newVal.maxStock,
      remark: newVal.remark
    }
  } else {
    form.value = {
      productId: null,
      currentStock: 0,
      unit: '',
      minStock: 0,
      maxStock: 0,
      remark: ''
    }
  }
}, { immediate: true })

const handleProductChange = (productId: number) => {
  const product = props.products.find(p => p.id === productId)
  if (product) {
    form.value.unit = product.unit
  }
}

const handleAdjustTypeChange = () => {
  // 调整类型变化时重置调整数量
  adjustAmount.value = 0
}

const handleClose = () => {
  visible.value = false
  emit('close')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 处理库存调整
        let finalStock = form.value.currentStock
        if (adjustType.value === 'increase') {
          finalStock += adjustAmount.value
        } else if (adjustType.value === 'decrease') {
          finalStock -= adjustAmount.value
        } else if (adjustType.value === 'set') {
          finalStock = adjustAmount.value
        }
        
        const submitData = {
          ...form.value,
          currentStock: finalStock,
          adjustType: adjustType.value,
          adjustAmount: adjustAmount.value,
          adjustReason: adjustReason.value
        }
        
        emit('submit', submitData)
        handleClose()
        ElMessage.success(`${props.editingItem ? '更新' : '保存'}成功`)
      } catch (error) {
        ElMessage.error(`${props.editingItem ? '更新' : '保存'}失败`)
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.inventory-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.inventory-form {
  max-height: 70vh;
  overflow-y: auto;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 单选框悬停效果 */
.radio-item {
  transition: all 0.3s ease;
}

.radio-item:hover {
  transform: scale(1.05);
}

/* 按钮悬停效果 */
.cancel-btn,
.submit-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.cancel-btn:hover,
.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.cancel-btn:active,
.submit-btn:active {
  transform: translateY(0);
}

.cancel-btn::after,
.submit-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.cancel-btn:active::after,
.submit-btn:active::after {
  width: 300px;
  height: 300px;
}

/* 取消按钮特殊样式 */
.cancel-btn {
  background-color: #909399;
  border-color: #909399;
  color: white;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

/* 提交按钮特殊样式 */
.submit-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.submit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-dialog {
    width: 95% !important;
    margin-top: 20px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-col {
    width: 100%;
  }
}
</style>